﻿@page "/vaccinationPoint/list"

@using BootstrapBlazor.Components;
@using System.Collections.Concurrent
@using BootstrapBlazorApp.Shared.Client
@using BootstrapBlazorApp.Shared.Models.Sites
@using System.Diagnostics.CodeAnalysis
@using BootstrapBlazorApp.Shared.Models.VaccinationPoint

@inject VaccinationPointClient _vaccinationPointClient

<Table TItem="VaccinationPointModel"
       IsPagination="true" PageItemsSource="@PageItemsSource"
       ShowToolbar="true" ShowSearch="true" IsMultipleSelect="true" ShowExtendButtons="true"
       ShowSearchText="true" ShowCardView ShowColumnList AllowResizing ShowLoading
       FixedExtendButtonsColumn="true" ExtendButtonColumnWidth="160"
       IsFixedHeader="true"
       Height="600"
       AddModalTitle="增加站点" EditModalTitle="编辑站点"
       SearchModel="@SearchModel" ShowEmpty="true" SearchMode="SearchMode.Top"
       OnQueryAsync="@OnQueryAsync" OnResetSearchAsync="@OnResetSearchAsync"
       OnAddAsync="@OnAddAsync" OnSaveAsync="@OnSaveAsync" OnDeleteAsync="@OnDeleteAsync">
    <TableColumns>
        <TableColumn @bind-Field="@context.Name" />
        <TableColumn @bind-Field="@context.Address" />
        <TableColumn @bind-Field="@context.Phone" />
        <TableColumn @bind-Field="@context.Principal" />
    </TableColumns>
    <TableToolbarTemplate>
      
    </TableToolbarTemplate>
    <SearchTemplate>
        <GroupBox Title="搜索条件">
            <div class="row g-3 form-inline">
                <div class="col-3 col-sm-3">
                    <BootstrapInput @bind-Value="@context.Name" placeholder="请输入名称" maxlength="30" ShowLabel="true" DisplayText="站点名称" />
                </div>
                <div class="col-3 col-sm-3">
                    <BootstrapInput @bind-Value="@context.Address" placeholder="请输入地址" maxlength="60" ShowLabel="true" DisplayText="站点地址" />
                </div>
            </div>
        </GroupBox>
    </SearchTemplate>
     <RowButtonTemplate>
        <TableCellButton Size="Size.ExtraSmall" Color="Color.Primary" Icon="fa fa-edit" Text="明细" OnClickCallback="@(() => OnRowButtonClick(context))" />
        
    </RowButtonTemplate>
</Table>


@code{

    private static readonly
            ConcurrentDictionary<Type, Func<IEnumerable<VaccinationPointModel>, string, SortOrder, IEnumerable<VaccinationPointModel>>>
            SortLambdaCache = new();

    private VaccinationPointModel SearchModel { get; set; } = new VaccinationPointModel();

    private static IEnumerable<int> PageItemsSource => new int[] { 20, 50, 100 };

    private List<VaccinationPointModel>? Items { get; set; } = new List<VaccinationPointModel>();

    /// <summary>
    /// OnInitialized 方法
    /// </summary>
    protected override async Task OnInitializedAsync()
    {
        await this.PagingAsync();
        await base.OnInitializedAsync();
    }

    private static Task<VaccinationPointModel> OnAddAsync() =>
        Task.FromResult(new VaccinationPointModel());

    /// <summary>
    /// 保存站点信息
    /// </summary>
    /// <param name="item"></param>
    /// <param name="changedType"></param>
    /// <returns></returns>
    private async Task<bool> OnSaveAsync(VaccinationPointModel item, ItemChangedType changedType)
    {
        if (changedType == ItemChangedType.Add)
        {
            await this.CreateAsync(item);
        }
        else
        {
            await this.UpdateAsync(item);
        }

        await this.PagingAsync();

        return true;
    }

    private async Task<bool> OnDeleteAsync(IEnumerable<VaccinationPointModel> items)
    {
        var keyIds = items.Select(item => item.Id).ToArray();
        foreach (var id in keyIds)
        {
             await this.RemoveAsync(id);
        }
       
        await this.PagingAsync();

        return true;
    }

    private static Task OnResetSearchAsync(VaccinationPointModel item)
    {
        item.Name = "";
        item.Address = "";
        return Task.CompletedTask;
    }

    private Task<QueryData<VaccinationPointModel>> OnQueryAsync(QueryPageOptions options)
    {
        IEnumerable<VaccinationPointModel> items = Items;

        // 处理高级搜索
        if (!string.IsNullOrEmpty(SearchModel.Name))
        {
            items = items.Where(item =>
                item.Name?.Contains(SearchModel.Name, StringComparison.OrdinalIgnoreCase) ?? false);
        }

        if (!string.IsNullOrEmpty(SearchModel.Name))
        {
            //items = items.Where(item => item.)?.Contains(SearchModel.), StringComparison.OrdinalIgnoreCase) ?? false);
        }

        // 处理 Searchable=true 列与 SeachText 模糊搜索
        if (options.Searchs.Any())
        {
            items = items.Where(options.Searchs.GetFilterFunc<VaccinationPointModel>(FilterLogic.Or));
        }
        else
        {
            // 处理 SearchText 模糊搜索
            if (!string.IsNullOrEmpty(options.SearchText))
            {
                items = items.Where(item => (item.Name?.Contains(options.SearchText) ?? false)
                                            || (item.Name?.Contains(options.SearchText) ?? false));
            }
        }

        // 过滤
        var isFiltered = false;
        if (options.Filters.Any())
        {
            items = items.Where(options.Filters.GetFilterFunc<VaccinationPointModel>());
            isFiltered = true;
        }

        // 排序
        var isSorted = false;
        if (!string.IsNullOrEmpty(options.SortName))
        {
            //var invoker = SortLambdaCache.GetOrAdd(typeof(UserTableModel), key => LambdaExtensions.GetSortLambda<UserTableModel>().Compile());
            //items = invoker(items, options.SortName, options.SortOrder);
            isSorted = true;
        }

        // 设置记录总数
        var total = items.Count();

        // 内存分页
        items = items.Skip((options.PageIndex - 1) * options.PageItems).Take(options.PageItems).ToList();

        return Task.FromResult(new QueryData<VaccinationPointModel>()
            {
                Items = items,
                TotalCount = total,
                IsSorted = isSorted,
                IsFiltered = isFiltered,
                IsSearch = !string.IsNullOrEmpty(SearchModel.Name) || !string.IsNullOrEmpty(SearchModel.Name)
            });
    }

    [Inject]
    [NotNull]
    private ToastService? ToastService { get; set; }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="item"></param>
    private async Task OnRowButtonClick(VaccinationPointModel item)
    {
        var cate = ToastCategory.Success;
        var title = "行内按钮处理方法";
        var content = "通过不同的函数区分按钮处理逻辑，参数 Item 为当前行数据";
        await ToastService.Show(new ToastOption()
            {
                Category = cate,
                Title = title,
                Content = content
            });
    }

    #region Service服务调用

    /// <summary>
    /// 添加站点信息
    /// </summary>
    /// <param name="item"></param>
    /// <returns></returns>
    public async Task CreateAsync(VaccinationPointModel item)
    {
        await  _vaccinationPointClient.CreateAsync(item);

    }

    /// <summary>
    /// 加载站点列表
    /// </summary>
    /// <returns></returns>
    public async Task PagingAsync()
    {
        var result = await  _vaccinationPointClient.GetAllListAsync();

        Items = result?.ToList();
    }

    /// <summary>
    /// 删除站点
    /// </summary>
    /// <param name="keyIds"></param>
    public async Task RemoveAsync(Guid id)
    {
        await _vaccinationPointClient.DeleteAsync(id);
    }

    /// <summary>
    /// 更新站点信息
    /// </summary>
    /// <param name="item"></param>
    public async Task UpdateAsync(VaccinationPointModel item)
    {
        await _vaccinationPointClient.UpdateAsync(item.Id,item);
    }

    #endregion

}
